/*
 * @Author: 丁平|1572804782@qq.com(dingping)
 * @Date: 2022-02-12
 * @LastEditors: 周润玉|zhourunyu1@outlook.com(zhourunyu)
 * @LastEditTime: 2022-07-27 10:44:53
 * @Description: 
 * @Administrator: 丁平|1572804782@qq.com(dingping)
 * @Copyright: 1.0.4
 */

import workreportmainApi from '../../../../../../public/js/common/api/mybusiness/workreport/workreportmain.api.js'
import ContactAPI from '../../../../../../public/js/common/api/mybusiness/workreport/reportcontact.api.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../../../../public/js/common/api/file-request.js";
const _portrait = '../../../../../public/static/images/other/pic_default_headimg.png';
const _file = '../../../../../public/static/images/other/pic_default_uploader.png';
/**
 *@file工作汇报编辑
 *@Date :2022-02-16 10:16:30
 *@create周润玉
*/

(function (window, document, $) {
    'use strict';
    let _vm;
    let uploader = null;
    const _page = {
        searchInfo: "",
        pageSize: 50,
        pageIndex: 0,
        status: "true",
        totalPages: -1
    };
    let employeesList = [];// 人员
    let checkboxList = [];// 选中人员ID
    let checkEmploy = [];// 提交数据

    $(function () {
        $('body').attr('data-weui-theme', 'light');
        _vm = new Vue({
            el: "#main-mine-data-edit",
            data() {
                return {
                    formObject: {},
                    modalData: {
                        bidResultEntryId: "",
                        bidResultId: "",
                    },
                    //expectedTimeLoading: '',
                    uploadCount: 0,
                    wordNumber: 0,
                    images: [],///处理weui自带上传插件回显重新上传时的问题
                    contents: '',
                    plans: "",
                    isNothing: true,
                    // quickQuery: '',
                    page: { ..._page },
                    ischeckboxNum: 0
                }
            },
            methods: {
                truckLoadingTime: function (param) {
                    // 保存当前的滚动距离
                    scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                    // 设置 fixed 布局
                    document.body.style.position = 'fixed';
                    document.body.style.height = '100%';
                    document.body.style.width = '100%';

                    // $("#datetime-picker").datetimePicker();
                    // isWhichTime()
                }
            }
        });
        initCommand();
        uploadInit();


        $('#returnPage').on('click', function () {
            history.go(-1)
        })
    });


    //TODO : 命令初始化
    //Date :2022-02-16 10:18:50
    //create周润玉  
    const initCommand = () => {
        //选择汇报对象
        $(".reportLead").on('click', function () {
            $("#report-contact").popup();
            $("#content").empty();
            refreshQuery();
        });

        //TODO : 编辑
        //Date :2022-02-16 10:18:38
        //create周润玉 
        let _json = Utils.ParsingUrl(window.location);
        workreportmainApi.getWkrptsBillDetail(_json.id).then(res => {
            let { id, reportType, reportStartDate, reportEndDate, contents, plans, attachments, recipients } = res;

            let _contentTitle = $("#contentTitle"), _planTitle = $("#planTitle"), _edittodayContent = $('#edittodayContent'), _edittomorrowPlan = $('#edittomorrowPlan');
            _edittodayContent.val(contents);// 汇报赋值
            _edittomorrowPlan.val(plans);// 计划赋值
            let _titleContent = {// 需要修改的标题 或者 文本域的提示内容
                1: { content: "今日工作内容", plan: "明日计划", setTime: moment(reportEndDate).format('YYYY-MM-DD') },
                2: { content: "本周工作内容", plan: "下周计划", setTime: moment(reportEndDate).format('YYYY-MM-DD') + `(第 ${moment(reportEndDate, "YYYY-MM-DD").isoWeek()} 周)` },
                3: { content: "本月工作内容", plan: "下月计划", setTime: moment(reportEndDate).format('YYYY-MM') },
                4: { content: "工作内容", plan: "下阶段计划", setTime: moment(reportStartDate).format('YYYY-MM-DD') + ' 至 ' + moment(reportEndDate).format('YYYY-MM-DD') }
            }
            let { content, plan, setTime } = _titleContent[reportType];
            _contentTitle.html(`${content}<span class="red-900">&nbsp;*</span>`)
            _planTitle.text(plan)
            _edittodayContent.attr("placeholder", `请输入${content}...`)
            _edittomorrowPlan.attr("placeholder", `请输入${plan}...`)

            $('#statDate').val(setTime);
            // $('#endDate').val(moment(reportEndDate).format('YYYY-MM-DD'));
            $('#reportSelect').val(reportType).trigger("change");
            if (Utils.IsNotNull(attachments)) {
                _images(attachments);
            }
            $("#choose").text(`已选择:${recipients.length}人`);
            $('#subEmployees').text(`确定(${recipients.length})`);
            checkEmploy = recipients;
            checkboxList = recipients.map(item => item.id);
            editEmployees();
        });

        //TODO : 汇报提交
        //Date :2022-02-16 10:19:09
        //create周润玉  
        $('#reportSubmit').on('click', async function () {
            let contents = $('#edittodayContent').val();
            let plans = $('#edittomorrowPlan').val();
            let type = $('#reportSelect').val();
            switch (type.toString()) {
                case '1'://日报
                    if (!Utils.IsNotNull(contents)) return $.toptip('今日工作不能为空', 'warning');
                    break;
                case '2'://周报
                    if (!Utils.IsNotNull(contents)) return $.toptip('本周工作不能为空', 'warning');
                    break;
                case '3'://月报
                    if (!Utils.IsNotNull(contents)) return $.toptip('本月工作不能为空', 'warning');
                    break;
                case '4'://汇报
                    if (!Utils.IsNotNull(contents)) return $.toptip('工作内容不能为空', 'warning');
                    break;
            }
            let _atteValue = [];
            let loadFiles = $("#uploaderFiles li");
            $.each(loadFiles, function (i, v) {
                let data = v.dataset;
                let itense = { "id": data.imageId, "name": data.name, "suffix": data.suffix };
                _atteValue.push(itense);
            });
            if (!Utils.IsNotNull(checkEmploy)) {
                return $.toptip('请选择汇报对象', 'warning');
            }
            // 增加关联员工是否正确校验
            // let _employ = await workreportmainApi.getLoginUserToStaff();
            // let empqueryJSon = {
            //     searchInfo: _employ?.numCode,
            //     pageIndex: 0,
            //     pageSize: 10,
            //     status: true
            // }
            // let empleInfo = await ContactAPI.queryEmployees(empqueryJSon)
            // let empleList = empleInfo.items
            // let flag = empleList.some(item => item.id == _employ?.id && item.name == _employ?.name)
            // if (flag == false) {
            //     return $.toptip(`关联员工有误，请联系管理员!`, 'warning');
            // }
            let editdata = {
                "contents": contents,
                "plans": plans,
                "recipients": checkEmploy,
                "attachments": _atteValue
            }
            let _json = Utils.ParsingUrl(window.location);
            workreportmainApi.updateWkrptsBill(_json.id, editdata).then(res => {
                if (res.isSucceed) {
                    setTimeout(() => { window.history.back(-1); }, 250);
                }
                $.toast("修改成功");
            });
        });
    }

    //TODO : 附件信息回显
    //Date :2022-02-16 10:19:26
    //create周润玉  
    const _images = async (file) => {
        let _imag = file;
        if (_imag) {
            if (!uploader) {
                await uploadInit();
            }
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i].id).then(_res => {
                    _vm.images.push({
                        id: _sun,
                        url: _res.data,
                        name: _imag[i].name,
                        imageId: _imag[i].id,
                        suffix: _imag[i].suffix
                    });
                    if (_res.isSucceed) {
                        let _li;
                        if (["jpg", "jpeg", "png", 'gif'].indexOf(_imag[i].suffix) < 0) {
                            _li = `<li class="weui-uploader__file" data-name="${_imag[i].name}" data-suffix="${_imag[i].suffix}" data-id="${_sun}" data-url="${_file}" data-image-id="${_imag[i].id}" style="background-image: url(${_file}) "></li>`;
                        } else {
                            _li = `<li class="weui-uploader__file" data-name="${_imag[i].name}" data-suffix="${_imag[i].suffix}" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i].id}" style="background-image: url(${_res.data}) "></li>`;

                        }
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $(".weui-uploader__input-box").hide();
            }
            _vm.uploadCount = _sun;
        }
    }

    //TODO : 附件上传
    //Date :2022-02-16 10:19:40
    //create周润玉  
    const uploadInit = async () => {
        uploader = weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                if (this.size > 8 * 1024 * 1024) {
                    $.toptip('请上传不超过8M的文件', 'warning');
                    return false;
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
                // return true; // 阻止默认行为，不插入预览图的框架
            },
            onQueued: function () {
                let formFile = new FormData();
                let upFiles = this;
                let file = publicFileDraw(this.name, _vm);
                if (file != false && file != undefined) {
                    $('.weui-uploader__file-content').hide();
                    $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                    formFile.append('apiobjfile', new window.File([this], file, { type: this.type }));
                    _uploadFileDraw(formFile, upFiles, _vm, file);
                }
                //确认提交
                $('.weui-dialog__btn').on('click', function () {
                    if ($(this)[0].innerHTML == '确认') {
                        $('.weui-uploader__file-content').hide();
                        $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                        let fileName = sliceFileName(upFiles);
                        let newfile = publicFileDraw(fileName, _vm);
                        if (newfile != false && newfile != undefined) {
                            formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                            _uploadFileDraw(formFile, upFiles, _vm, newfile);
                        }
                    }
                });
                return true;
            }
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.images = _vm.images.filter(item => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $(".weui-uploader__input-box").hide();
                            } else {
                                $(".weui-uploader__input-box").show();
                            }
                        },
                        onCancel: function () {
                        }
                    });
                }
            });
        });
    }

    /**
     *@file
     *@Date :2022-07-26 11:56:21
     *@create周润玉
    */
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile).then(res => {
            if (res.isSucceed) {
                let _list = _vm.images;
                _list.push({
                    id: $("#uploaderFiles li").length,
                    imageId: res.data,
                    url: upFiles.url,
                    name: newName,
                    suffix: upFiles.name.split('.').pop().toLowerCase() //获取文件后缀名称
                });
                _vm.images = _list;
                $("#uploaderFiles li").each(function (i) {
                    $(this).attr('data-id', _vm.images[i].id);
                    $(this).attr('data-image-id', _vm.images[i].imageId);
                    $(this).attr('data-name', _vm.images[i].name);
                    $(this).attr('data-suffix', _vm.images[i].suffix);
                    if (["jpg", "jpeg", "png", 'gif'].indexOf(_vm.images[i].suffix) < 0) {
                        $(this).attr('data-url', _file);
                        $(this).css({ 'background-image': `url(${_file})` });
                    } else {
                        $(this).attr('data-url', _vm.images[i].url);
                        $(this).css({ 'background-image': `url(${_vm.images[i].url})` });
                    }
                });
            }
        }).catch(res => {
            $("#uploaderFiles li").eq($("#uploaderFiles li").length - 1).remove();
            _vm.uploadCount = --_vm.uploadCount;
            $.toptip(res.msg, 'error');
        }).finally(_ => {
            $.hideLoading();
            $.closeModal();
        });
    }

    //查询汇报对象信息
    const refreshQuery = () => {
        let _page = { "searchInfo": $('#searchInput').val(), "pageIndex": 0, "totalPages": -1, "pageSize": 50, "status": true };
        _vm._data.page = Object.assign(_vm._data.page, _page);
        queryEmployeesList();
    }
    function unique(arr) {
        const res = new Map();
        return JSON.parse(JSON.stringify(arr)).filter((a) => !res.has(a.id) && res.set(a.id, 1))
    }
    //操作汇报对象
    const queryEmployeesList = () => {
        let _data = _vm._data.page;
        let _list = [];
        ContactAPI.queryEmployees(_data).then(res => {
            let _page = {
                searchInfo: $('#searchInput').val(),
                pageSize: 50,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages,
                status: true
            }
            _vm._data.page = Object.assign({}, _page);
            if (!Utils.IsNotNull($('#searchInput').val()) && _data.pageIndex == 0) {
                _list.push(...checkEmploy);
            }
            _list.push(...res.items);
            unique(_list).map(item => {
                let labhtml = `<label class="weui-cell weui-cell_active weui-check__label" for="${item.id}" data-id="${item.id}" id="lab_${item.id}">
                    <div class="weui-cell__hd">
                        <input type="checkbox" class="weui-check" name="checkbox1" id="${item.id}">
                        <i class="weui-icon-checked"></i>
                    </div>
                    <div class="weui-cell__hd" aria-hidden="true" style="position: relative;">
                        <img src="${_portrait}" alt="" class="headPortrait"
                            style="width: 50px;display: block;">
                    </div>
                    <div class="weui-cell__bd" aria-hidden="true">
                        <span class="lab_name">${item.name}</span>
                        <div class="demo_badge_desc lab_numCode">工号：${item.numCode}</div>
                    </div>
                </label>`
                $("#content").append(labhtml);
            });
            checkboxList.map(item => $(`#${item}`).prop("checked", true));
            employeesList = [...employeesList, ...res.items];
        });
    }

    //
    const editEmployees = () => {
        weui.searchBar('#searchInput');
        //TODO : 员工上拉加载
        $("#iscroll").infinite().on("infinite", function () {
            let _data = _vm._data.page;
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                queryEmployeesList();
                self.loading = false;
            }, 500);   //模拟延迟
        });
        $("#searchdiv form").submit(function () {
            _mainSearch();
            return false;
        }).on("input propertychange", Utils.throttle(_mainSearch, 500));
        search();
        $(document).on('click', '#iscroll .weui-check__label', function (event) { // 搜索回车事件
            // event.stopPropagation();   //表示阻止向父元素冒泡
            event.preventDefault();     //阻止 方法阻止元素发生默认的行为（例如，当点击提交按钮时阻止对表单的提交或者a标签）
            let isChecked = $(this).find("input[type='checkbox']").is(':checked')
            $(this).find("input[type='checkbox']").prop("checked", !isChecked);
            if (!isChecked == true && checkboxList.includes($(this).data("id")) == false) {
                checkboxList.push($(this).data("id"));
            } else {
                checkboxList.splice(checkboxList.indexOf($(this).data("id")), 1);
            }
            $('#subEmployees').text(`确定(${checkboxList.length})`);
            $("#choose").text(`已选择:${checkboxList.length}人`);
        });

        // 选择推送对象完成时
        $("#subEmployees").on('click', function () {
            let subData = [...checkboxList.map(item => { return [...employeesList, ...checkEmploy].find(item1 => item1.id == item); })] || [];
            checkEmploy = subData;
            $.closePopup();
            $('#searchInput').val("");
            $('#searchBar').removeClass("weui-search-bar_focusing");
        });
        // 取消按钮
        $("#cancelSub").on('click', function () {
            let checkHistory = [...checkEmploy.map(item => { return item.id })] || [];// 点取消时的上一次数据
            checkboxList = checkHistory;// 上一次点 确定的数据  赋值给  选中的数据
            $('#subEmployees').text(`确定(${checkboxList.length})`);
            $("#choose").text(`已选择:${checkboxList.length}人`);
            $.closePopup();
            $('#searchInput').val("");
            $('#searchBar').removeClass("weui-search-bar_focusing");
        });
    }

    ///输入框
    const _mainSearch = function () {
        let _page = { "searchInfo": $('#searchInput').val(), "pageIndex": 0, "totalPages": -1, "pageSize": 50, "status": true };
        _vm._data.page = Object.assign(_vm._data.page, _page);
        $("#content").empty();
        queryEmployeesList();
    };

    //
    const search = () => {
        let $searchBar = $('#searchBar'),
            $searchResult = $('#searchResult'),
            $searchText = $('#searchText'),
            $searchInput = $('#searchInput'),
            $searchClear = $('#searchClear'),
            $searchForm = $('#searchForm'),
            $searchCancel = $('#searchCancel');

        function hideSearchResult() {
            $searchResult.hide();
            $searchForm.attr('aria-expanded', 'false');
            $searchInput.val('');
        }
        function cancelSearch() {
            hideSearchResult();
            $searchBar.removeClass('weui-search-bar_focusing');
            $searchText.show();
        }

        $searchText.on('click', function () {
            $searchBar.addClass('weui-search-bar_focusing');
            $searchInput.focus();
        });

        $searchInput
            .on('blur', function () {
                if (!this.value.length) cancelSearch();
            })
            .on('input', function () {
                if (this.value.length) {
                    $searchResult.show();
                    $searchForm.attr('aria-expanded', 'true');
                } else {
                    $("#content").empty();
                    //refreshQuery();
                    $searchResult.hide();
                    $searchForm.attr('aria-expanded', 'false');
                }
            });
        $searchClear.on('click', function () {
            hideSearchResult();
            $searchInput.focus();
            $("#content").empty();
            refreshQuery()
        });
        $searchCancel.on('click', function () {
            cancelSearch();
            $("#content").empty();
            refreshQuery();
            $searchInput.blur();
        });
    }

})(window, document, jQuery)